/*
 * @Author: Wangtao
 * @Date: 2020-10-26 16:20:34
 * @LastEditors: Wangtao
 * @LastEditTime: 2020-11-27 20:37:27
 */
import { VuexModule, Module, Action, getModule, Mutation } from 'vuex-module-decorators'
import { commonAction } from '@/utils/common'
import Vue from 'vue'
import store from '@/store'

@Module({ dynamic: true, name: 'ivr', store, namespaced: false })
class Ivr extends VuexModule {
  public cacheSign: boolean = false
  public selectCache: any = {}
  public voiceTransfer: any = {}

  @Mutation
  private SET_SELECT_CACHE ({ key, value }) {
    Vue.set(this.selectCache, key, value)
  }

  @Mutation
  private SET_CACHE_SIGN (SIGN) {
    this.cacheSign = SIGN
  }

  @Mutation
  public setVoiceTransfer (data: any) {
    this.voiceTransfer = data
  }

  @Action
  public async IvrCommonAction (parame: object) {
    return commonAction(parame).then(resp => {
      return resp
    })
  }

  @Action({ rawError: true })
  public async getNodeCache () {
    // 服务号列表 语音库列表 时间条件缓存
    const callCatchRequest = Vue.prototype.$getCache('/call/action/general/query', [
      'voiceLibraryList',
      'timeConditionList'
    ], false)
    const basicsCatchrequest = Vue.prototype.$getCache('/base/action/general/cache/query', ['queueList'], false)
    return Promise.all([callCatchRequest, basicsCatchrequest]).then((result) => {
      if (result[0].success && result[1].success) {
        this.SET_CACHE_SIGN(true)
      }
      if (result[0].success) {
        [
          'voiceLibraryList',
          'timeConditionList'
        ].forEach(type => {
          this.SET_SELECT_CACHE({ key: type, value: result[0][type] })
        })
      }

      if (result[1].success) {
        ['queueList'].forEach(type => {
          this.SET_SELECT_CACHE({ key: type, value: result[1][type] })
        })
      }
    })
  }

  @Action
  public getAvailableNumberList ({ numbers }) {
    const availableServiceNumberList = Vue.prototype.$getCache('/call/action/general/query', [
      'availableServiceNumberList'
    ], false, true)
    const serviceNumberList = Vue.prototype.$getCache('/call/action/general/query', [
      'serviceNumberList'
    ], false)
    return Promise.all([availableServiceNumberList, serviceNumberList]).then(([res1, res2]) => {
      const serviceList: any = []
      let avaList = res1.availableServiceNumberList || []
      avaList = avaList.filter(item => {
        return (numbers.indexOf(item.number) === -1)
      })
      numbers.forEach(num => {
        (res2 as any).serviceNumberList.some((item) => {
          if (num === item.number) {
            serviceList.push(item)
            return true
          }
        })
      })
      return serviceList.concat(avaList)
    })
  }

  @Action
  public async setSelectCache ({ key, value }) {
    this.SET_SELECT_CACHE({ key, value })
  }
}

export const IvrModule = getModule(Ivr)
